/**
 * 
 */
package com.google.code.jkippt.parser;

import java.io.IOException;

import com.google.code.jkippt.resource.Clip;
import com.google.code.jkippt.resource.ClipList;
import com.google.gson.JsonElement;
import com.google.gson.JsonNull;
import com.google.gson.JsonObject;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;

/**
 * Serialize list field as a string using the cliplist resource uri field.
 * @author "Federico De Faveri defaveri@gmail.com"
 */
public class ClipAdapter extends TypeAdapter<Clip> {

	protected TypeAdapter<Clip> defaultAdapter;
	protected TypeAdapter<JsonElement> jsonElementAdapter;

	/**
	 * @param defaultAdapter
	 * @param jsonElementAdapter
	 */
	public ClipAdapter(TypeAdapter<Clip> defaultAdapter,
			TypeAdapter<JsonElement> jsonElementAdapter) {
		this.defaultAdapter = defaultAdapter;
		this.jsonElementAdapter = jsonElementAdapter;
	}

	/** 
	 * {@inheritDoc} 
	 */
	@Override
	public void write(JsonWriter out, Clip value) throws IOException {
		if (value == null || value.getList() == null) defaultAdapter.write(out, value);
		else {
			JsonElement jsonElement = defaultAdapter.toJsonTree(value);
			assert(jsonElement.isJsonObject());
			JsonObject jsonObject = jsonElement.getAsJsonObject();
			ClipList list = value.getList();
			
			if (list.getResourceUri()==null) jsonObject.add("list", JsonNull.INSTANCE);
			else jsonObject.addProperty("list", value.getList().getResourceUri());
			jsonElementAdapter.write(out, jsonObject);
		}
	}

	/** 
	 * {@inheritDoc} 
	 */
	@Override
	public Clip read(JsonReader in) throws IOException {
		return defaultAdapter.read(in);
	}

}
